package com.jd.risk.bankorder.util;

import java.io.File;
import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service(value="mailSender")
public class MailSender {

	private Logger logger = Logger.getLogger(MailSender.class);

	@Value("${mail.audit.from}")
	private String aduitForm = "wysafetycenter@jd.com";
	
	@Autowired
	@Qualifier(value = "mailSenderTelecom")
	private JavaMailSenderImpl mailSender;
	
	public boolean sendMail(String sendTo,String subject,String date,String from,String text){
		return sendMail(sendTo, subject, date, null, from, text,null);
	}
	
	public boolean sendMail(String sendTo,String subject,String text,String cc,JavaMailSenderImpl mailSender,String from){
		return sendMail(sendTo,subject,null,null,from,text,cc);
	}
	
	public boolean sendMail(String sendTo,String subject,String date,File file,String from,String text,String cc){
		logger.info("开始邮件发送。。。");
		try {
			MimeMessage msg = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GBK");
			helper.setFrom(from);
			if(cc!=null&&!"".equals(cc))
				helper.setCc(cc.split(","));
			helper.setTo(sendTo.split(","));
			helper.setSubject( subject + (date==null?"":("_" + date)));
			helper.setText(text,false);
			if(file != null)
				helper.addAttachment(MimeUtility.encodeWord(file.getName()),file);
			mailSender.send(msg);
			logger.info("邮件发送完成。。。。");
			return true;
		} catch (MailException e) {
			logger.error("邮件发送失败！！！", e);
		} catch (UnsupportedEncodingException e) {
			logger.error("邮件发送失败！！！", e);
		} catch (MessagingException e) {
			logger.error("邮件发送失败！！！", e);
		}
		return false;
	}

}
